# Libraries
# library(tidyverse)
# library(rio)
# library(here)
# library(fixest)
# library(lubridate)

# data_pnas = import(here("Data","data_pnas.rds"))

in_vars = c("norm_judgesre","norm_loyaltyre","norm_pollingre",
            "norm_executivere","norm_censorshipre", paste0("violence",3:6,"re"))

# Identify panel respondents
multi_id = data_pnas |>
  count(uid) |> 
  filter(n > 1) |> 
  pull(uid)

data_multi = filter(data_pnas, uid %in% multi_id)

# Lagged IV
data_lagged = data_multi |> 
  arrange(date) |> 
  group_by(uid) |> 
  mutate(across(all_of(in_vars), lag, .names = "{.col}_lag"),
         weight = weight * wt_adj) |>
  ungroup()

lagged_reg = map(in_vars, \(x){
  feols(as.formula(paste0(x, "~ ",x,"_lag")),
        data = data_lagged, weights = data_lagged$weight)
})
names(lagged_reg) = in_vars

etable(lagged_reg[1:5], 
       signif.code = c("***"=0.001, "**"=0.01, "*"=0.05),
       file = here("Tables","Supplementary","table_s12.tex"), replace = T)
etable(lagged_reg[6:9], 
       signif.code = c("***"=0.001, "**"=0.01, "*"=0.05),
       file = here("Tables","Supplementary","table_s13.tex"), replace = T)